package com.wushijia.highconcurrency.thread;

public class InterruptTest2 {

  public static void main(String[] args) throws InterruptedException {
    Thread t1 = new Thread() {
      @Override
      public void run() {
        while (true) {
          if (Thread.currentThread().isInterrupted()) {
            System.out.println("Interrupted");
            break;
          }
          try {
            Thread.sleep(2000);
            System.out.println("sleep...");
          } catch (InterruptedException e) {
            System.out.println("sleep interrupted");
            //sleep方法会由于中断而抛出异常，但它会清除中断标记，如果不加处理，在下次循环时将无法获得中断标记，因此在异常处理中设置中断标记位，去掉也行，有优化？
//            Thread.currentThread().interrupt();
          }
          Thread.yield();
        }
      }
    };

    t1.start();
    //为了让t1线程有机会进入睡眠状态，然后再去中断
    Thread.sleep(2000);
    t1.interrupt();
  }
}
